﻿import { SettingsService } from '@delon/theme';
import { Component, Injector, OnInit, ViewChild } from '@angular/core';
import { AppComponentBase } from "@shared/component-base/app-component-base";
import { HttpClient, HttpParams } from '@angular/common/http';
import { CategoryDto, CategoryListQueryDto } from "@shared/model/categorydto";
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { CreateCategoryComponent } from './create-category.component';
import { EditCategoryComponent } from './edit-category.component';


@Component({
  templateUrl: './category.component.html'
})
export class CategoryComponent extends AppComponentBase implements OnInit{ 
  loading = false;
  dataSet: CategoryDto[] = [];
  listQuery: CategoryListQueryDto = new CategoryListQueryDto();
  mapOfExpandedData: { [id: string]: CategoryDto[] } = {};


  @ViewChild('createCategoryModal')
  createCategoryModal: CreateCategoryComponent;
  @ViewChild('editCategoryModal')
  editCategoryModal: EditCategoryComponent;

  constructor(
    private injector: Injector,
    private httpClient: HttpClient,
    private modalService: NzModalService,
    public msg: NzMessageService
  ) {
    super(injector);
  }

  ngOnInit(): void {
    this.list();
  }

  list(): void {
    this.loading = true;
    this.httpClient.post("category/pagelist", {}).subscribe(
      (val) => {
        const body: any = val;
        if (body && !body.success) {
          this.msg.error(body.message);
          return null;
        } else {
          this.dataSet = body.data;
          this.dataSet.forEach(item => {
            this.mapOfExpandedData[item.id+""] = this.convertTreeToList(item);
          })
        }
      },
      response => {
        this.loading = false;
        console.log("Login POST call in error", response);
      },
      () => {
        this.loading = false;
      });
  }

  collapse(array: CategoryDto[], data: CategoryDto, $event: boolean): void {
    if ($event === false) {
      if (data.children) {
        data.children.forEach(d => {
          const target = array.find(a => a.id === d.id)!;
          this.collapse(array, target, false);
        });
      } else {
        return;
      }
    }
  }

  convertTreeToList(root: CategoryDto): CategoryDto[] {
    const stack: any[] = [];
    const array: any[] = [];
    const hashMap = {};
    stack.push({ ...root, level: 0, expand: !!root.children });

    while (stack.length !== 0) {
      const node = stack.pop();
      this.visitNode(node, hashMap, array);
      if (node.children) {
        for (let i = node.children.length - 1; i >= 0; i--) {
          stack.push({ ...node.children[i], level: node.level + 1, expand: !!node.children, parent: node });
        }
      }
    }

    return array;
  }

  visitNode(node: CategoryDto, hashMap: { [key: string]: any }, array: CategoryDto[]): void {
    if (!hashMap[node.id+""]) {
      hashMap[node.id+""] = true;
      array.push(node);
    }
  }



  delete(category: CategoryDto): void {
    this.modalService.confirm({
      nzTitle: '你确定删除该条记录吗?',
      nzOnOk: () => {
        let params = new HttpParams().append('id', `${category.id}`);
        this.httpClient.get("category/delete", { params }).subscribe(
          (val) => {
            const result: any = val;
            if (result && !result.success) {
              this.msg.error(result.message);
              return null;
            } else {
              this.msg.success("删除成功！");
              this.list();
            }
          });
      }
    });
  }

  create(): void {
    this.createCategoryModal.showModal();
  }

  edit(category: CategoryDto): void {
    this.editCategoryModal.showModal(category.id);
  }
}

